package com.example.demo.web.services;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;

import com.example.demo.web.Entity.SysEntity;
import com.example.demo.web.Entity.UserEntity;
import com.example.demo.web.Entity.UserLogEntity;
import com.example.demo.web.dao.SysDAO;
import com.example.demo.web.util.XinLongUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Service
public class SysService {
	private SysDAO sysDao;
	
    @Autowired
    public void setSysDao(SysDAO sysDao){
        this.sysDao =sysDao;
    }
    
    public List<SysEntity> getSyslist(){
        return sysDao.findAll();
    }
    
    
    public String getSyslist(HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode res = mapper.createObjectNode();
    	ArrayNode rootnode = mapper.createArrayNode();
    	List<SysEntity> syslist = sysDao.findAll();
    	if(syslist != null && syslist.size()> 0){
			ObjectNode tjson = null;
			for(SysEntity sys : syslist){
				tjson = mapper.createObjectNode();
				tjson.put("id", sys.getId());
    			tjson.put("descriptor", sys.getDescriptor());
    			tjson.put("name", sys.getName());
    			tjson.put("sysvalue", sys.getSysvalue());
    			tjson.put("updatetime", sys.getUpdatetime());
    			rootnode.add(tjson);
    		}
		}    
    	
    	return mapper.writeValueAsString(rootnode);  
    }
    
    public void _sys_Edit(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	ObjectMapper mapper = new ObjectMapper(); 
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectNode res = mapper.createObjectNode();  
    	com.fasterxml.jackson.databind.JsonNode rootNode;		
    	String name = "";
    	String sysval = "";
    	String ckname = "";
		try{
			rootNode = mapper.readTree(jsonstr);
			name =rootNode.get("name").asText();
			sysval =rootNode.get("sysval").asText();
			ckname =rootNode.get("ckname").asText();
		}catch(Exception er){
			res.put("status", "0");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}
		//权限判断
    	/*res = XinLongUtil.OptAuth("",jsonstr, sentity);
		if(!res.get("status").asText().equals("1210")){
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}*/
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("系统管理/系统参数/修改参数");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("sys_Edit");
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setCreate_check_userid(ckname);
		SysEntity sys = sysDao.findByEntityName(name);
		
		if(sys != null){
			if(sys.getName().equals("system_debug") || sys.getName().equals("AllNeedCheck") || sys.getName().equals("login_try_no") || sys.getName().equals("updatePwdNeed")){
				//校验是否为int型数据
				try{
					int sysvalue = Integer.parseInt(sysval);					
				}catch(Exception ex){
					res.put("status", "2");
					res.put("desc", "失败!");
					ulog.setDescriptor(sysval + "必须为整数.");
					ulog.setProceed("操作失败");
					XinLongUtil.saveUserLog(ulog);
					deferredResult.setResult(mapper.writeValueAsString(res));
					return;
				}
			}
			if(sys.getName().equals("system_debug")){
				//校验是否为int型数据
				try{
					int sysvalue = Integer.parseInt(sysval);
					XinLongUtil.xinLongUtil.setDebugflag(sysvalue);
				}catch(Exception ex){
					res.put("status", "2");
					res.put("desc", "失败!");
					ulog.setDescriptor(sysval + "必须为整数.");
					ulog.setProceed("操作失败");
					XinLongUtil.saveUserLog(ulog);
					deferredResult.setResult(mapper.writeValueAsString(res));
					return;
				}
				
			}
			sys.setSysvalue(sysval);
			sys.setUpdatetime(dateFormat.format(date));
			if(sysDao.updatesys(sys) == 1){
				res.put("status", "1");
				res.put("desc", "成功!");
				ulog.setDescriptor(name + "参数被修改");
				ulog.setProceed("操作成功");
				XinLongUtil.saveUserLog(ulog);
				
			}else{
				res.put("status", "2");
				res.put("desc", "更新参数失败!");
			}
		}else{
			res.put("status", "2");
			res.put("desc", "查找参数失败!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
			
		}
		deferredResult.setResult(mapper.writeValueAsString(res));
		return; 
    }
}
